//
//  TTKStringUtils.m
//  AQUA
//
//  Created by 吕清毅 on 2018/8/2.
//  Copyright © 2018年 小河. All rights reserved.
//

#import "TTKStringUtils.h"
//引入IOS自带密码库
#import "CommonCrypto/CommonDigest.h"
#import <CommonCrypto/CommonCryptor.h>

@implementation TTKStringUtils


//是否为空
+ (BOOL)isEmpty:(NSString *)str {
    if (str && str.length > 0) {
        return false;
    }
    return true;
}

//格式化空串
+ (NSString *)formatEmpty:(NSString*)str {
    if ([str isEqualToString:@"0"] || str == nil || str == NULL || str.length == 0 || [str isEqualToString:@""] || [str isEqualToString:@"null"] || [str isEqualToString:@"(null)"] || [str isEqualToString:@"<null>"]) {
        return @" ";
    }
    return str;
}

//MD5加密
+ (NSString *)md5:(NSString *)inPutText
{
    const char *cStr = [inPutText UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (int)strlen(cStr), result);
    
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
}

//根据高度获取宽度
+ (CGSize)sizeWithText:(NSString *)text Height:(CGFloat)height Font:(UIFont*)font
{
    CGSize size = CGSizeMake(CGFLOAT_MAX,height);
    size = [text boundingRectWithSize:size options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil].size;
    return size;
}

//根据宽度获取高度
+ (CGSize)sizeWithText:(NSString *)text Width:(CGFloat)width Font:(UIFont*)font
{
    CGSize size = CGSizeMake(width,CGFLOAT_MAX);
    size = [text boundingRectWithSize:size options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil].size;
    return size;
}


// 字符个数统计
+ (int)charCounts:(NSString *)str {
    int strlength = 0;
    char* p = (char*)[str cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i<[str lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        if (*p) {
            p++;
            strlength++;
        }
        else {
            p++;
        }
    }
    return strlength;
}

//判断是否是手机号
+ (BOOL)isValidateMobile:(NSString *)str {
    NSString *mobile = str;
//    if (mobile.length != 11) {
//        return NO;
//    }
//
//    NSString *phone = @"^1(3[0-9]|4[57]|5[0-35-9]|7[0-9]|8[0-9])\\d{8}$";
//    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phone];
//
//    return  [regextestct evaluateWithObject:mobile] ;
    if (mobile.length >= 7 && mobile.length <= 11) {
        return YES;
    }
    return NO;
}

//判断是否是邮箱
+ (BOOL)isValidateEmail:(NSString *)str {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:str];
}

//判断银行账号
+ (BOOL)isValidateBank:(NSString *)str {
    NSString *bankNo=@"^\\d{16}|\\d{19}+$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",bankNo];
    return [phoneTest evaluateWithObject:str];
}

//判断银行卡格式
+ (BOOL) checkCardNo:(NSString*) cardNo{
    int oddsum = 0;     //奇数求和
    int evensum = 0;    //偶数求和
    int allsum = 0;
    int cardNoLength = (int)[cardNo length];
    int lastNum = [[cardNo substringFromIndex:cardNoLength-1] intValue];
    
    cardNo = [cardNo substringToIndex:cardNoLength - 1];
    for (int i = cardNoLength -1 ; i>=1;i--) {
        NSString *tmpString = [cardNo substringWithRange:NSMakeRange(i-1, 1)];
        int tmpVal = [tmpString intValue];
        if (cardNoLength % 2 ==1 ) {
            if((i % 2) == 0){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }else{
            if((i % 2) == 1){
                tmpVal *= 2;
                if(tmpVal>=10)
                    tmpVal -= 9;
                evensum += tmpVal;
            }else{
                oddsum += tmpVal;
            }
        }
    }
    
    allsum = oddsum + evensum;
    allsum += lastNum;
    if((allsum % 10) == 0)
        return YES;
    else
        return NO;
}

//密码（6~20位，数字，字母）
+ (BOOL)isValidatePassword:(NSString *)str {
    NSString *passWordRegex = @"^[a-zA-Z0-9]{8,20}+$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:str];
}

//判断身份证号
+ (BOOL)isValidateIdentityCard:(NSString *)str {
    NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    BOOL length= [identityCardPredicate evaluateWithObject:str];
    if (!length) {
        return length;
    }
    NSArray *pArr = @[

                      @"11",//北京市|110000，

                      @"12",//天津市|120000，

                      @"13",//河北省|130000，

                      @"14",//山西省|140000，

                      @"15",//内蒙古自治区|150000，

                      @"21",//辽宁省|210000，

                      @"22",//吉林省|220000，

                      @"23",//黑龙江省|230000，

                      @"31",//上海市|310000，

                      @"32",//江苏省|320000，

                      @"33",//浙江省|330000，

                      @"34",//安徽省|340000，

                      @"35",//福建省|350000，

                      @"36",//江西省|360000，

                      @"37",//山东省|370000，

                      @"41",//河南省|410000，

                      @"42",//湖北省|420000，

                      @"43",//湖南省|430000，

                      @"44",//广东省|440000，

                      @"45",//广西壮族自治区|450000，

                      @"46",//海南省|460000，

                      @"50",//重庆市|500000，

                      @"51",//四川省|510000，

                      @"52",//贵州省|520000，

                      @"53",//云南省|530000，

                      @"54",//西藏自治区|540000，

                      @"61",//陕西省|610000，

                      @"62",//甘肃省|620000，

                      @"63",//青海省|630000，

                      @"64",//宁夏回族自治区|640000，

                      @"65",//新疆维吾尔自治区|650000，

                      @"71",//台湾省（886)|710000,

                      @"81",//香港特别行政区（852)|810000，

                      @"82",//澳门特别行政区（853)|820000

                      ];

    NSString *idcard=[str uppercaseString];
    NSInteger lSumQT = 0;
    //加权因子
    int R[] = {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};

    //校验码
    unsigned char sChecker[11] = {'1','0','X','9','8','7','6','5','4','3','2'};

    NSMutableString *mString = [NSMutableString stringWithString:str];

    if (str.length == 15) {
        [mString insertString:@"19" atIndex:6];
        long p =0;

        //        const char *pid = [mString UTF8String];

        for (int i =0; i<17; i++)

        {

            NSString * s = [mString substringWithRange:NSMakeRange(i, 1)];

            p += [s intValue] * R[i];

        }

        int o = p%11;

        NSString *string_content = [NSString stringWithFormat:@"%c",sChecker[o]];

        [mString insertString:string_content atIndex:[mString length]];

        idcard = mString;
    }

    if (![pArr containsObject:[idcard substringToIndex:2]]) {
        return NO;
    }
    //判断年月日是否有效

    //年份
    int strYear = [[self getStringWithRange:idcard Value1:6 Value2:4] intValue];
    //月份
    int strMonth = [[self getStringWithRange:idcard Value1:10 Value2:2] intValue];

    //日
    int strDay = [[self getStringWithRange:idcard Value1:12 Value2:2] intValue];

    NSTimeZone *localZone = [NSTimeZone localTimeZone];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    [dateFormatter setTimeZone:localZone];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSDate *date = [dateFormatter dateFromString:[NSString stringWithFormat:@"%d-%02d-%02d 12:01:01",strYear,strMonth,strDay]];

    if (date == nil) {

        return NO;
    }
    NSString * lst = [idcard substringFromIndex:idcard.length-1];

    if (![self isNumber:lst] && ![lst isEqualToString:@"X"]) {
        return NO;
    }
    if ([[idcard substringFromIndex:idcard.length-1] integerValue]<10) {
    }
    for (int i = 0; i<17; i++){
        NSString * s = [idcard substringWithRange:NSMakeRange(i, 1)];
        lSumQT += [s intValue]*R[i];
    }
    const char *PaperId = [idcard UTF8String];
    if (sChecker[lSumQT%11] != PaperId[17]){
        return NO;
    }
    return YES;
}

+ (NSString *)getStringWithRange:(NSString *)str Value1:(NSInteger)v1 Value2:(NSInteger)v2{
    
    NSString * sub = [str substringWithRange:NSMakeRange(v1, v2)];
    
    return sub;
}
//正整数
+ (BOOL)isNumber:(NSString *)str {
    NSString *match=@"^[0-9]*$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:str];
}

+ (NSString *)deleteSpaceIn:(NSString *)str
{
    NSString *st = [str uppercaseString];
    NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
    NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];
    NSArray *parts = [st componentsSeparatedByCharactersInSet:whitespaces];
    NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
    st = [filteredArray componentsJoinedByString:@""];
//    st = [st stringByReplacingOccurrencesOfString:@" " withString:@""];
//    st = [st stringByReplacingOccurrencesOfString:@"\r\n" withString:@""]; //换行符是\r\n 而不是\n
//    // 去掉字符串首尾的空格和字符串
//    st = [st stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    return st;
}




@end
